package com.sparrow.servicemgr.consul.domain;

import com.ecwid.consul.v1.health.model.HealthService;
import com.sparrow.common.util.ConsistentHashing;
import com.sparrow.servicemgr.consul.ConsulManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConsistentServiceSelector {

    private final ConsulManager consulManager;
    private final int virtualNodeCount;
    private final String serviceNames;

    public ConsistentServiceSelector(ConsulManager consulManager, String serviceNames, int virtualNodeCount) {
        this.consulManager = consulManager;
        this.serviceNames = serviceNames;
        this.virtualNodeCount = virtualNodeCount;
    }

    public HealthService selectService(String key) {
        // 实时获取多个服务名下的健康节点
        List<HealthService> allServices = consulManager.getHealthServices(serviceNames);
        // 构建一致性哈希
        ConsistentHashing hash = new ConsistentHashing(virtualNodeCount);
        Map<String, HealthService> idToService = new HashMap<>();
        for (HealthService service : allServices) {
            String id = service.getService().getId();
            hash.addNode(id);
            idToService.put(id, service);
        }
        // 哈希选择节点
        String nodeId = hash.getNode("key-" + key);
        return idToService.get(nodeId);
    }
}

